package com.xuan.utils;

import com.alibaba.fastjson.JSON;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Admin
 */
public class GaodeMapUtil {
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    /**
     * 地理编码
     */
    public static GaoDeGeocode getGeocoding(String address) throws Exception {
        Request request = new Request.Builder()
            .url("https://restapi.amap.com/v3/geocode/geo?key=47192117cf2d5bda31326ca67183e2b9&output==JSON"+"&address="+address)
            .addHeader("Content-Type", "application/x-www-form-urlencoded")
            .addHeader("Accept", "application/json")
            .build();
        try {
            Response response = HTTP_CLIENT.newCall(request).execute();
            ResponseBody responseBody = response.body();
            // 将responseBody 转化为GaoDeGeocode对象
            GaoDeGeocode gaoDeGeocode = JSON.parseObject(responseBody.string(), GaoDeGeocode.class);
            return gaoDeGeocode;
        } catch (IOException e) {
            throw new Exception("地理编码失败");
        }
    }

    /**
     * 获取地址经纬度
     * @param address
     * @return
     */
    public static Map<String, String> getAddressLongitudeAndLatitude(String address) throws Exception {
        GaoDeGeocode geocoding = getGeocoding(address);
        Map<String, String> map = new HashMap<>();
        if(null != geocoding){
            map.put("lng", geocoding.getGeocodes().get(0).getLocation().split(",")[0]); // 经度
            map.put("lat", geocoding.getGeocodes().get(0).getLocation().split(",")[1]); // 纬度
        }
        return map;
    }

}
